package com.construction.ccb.ui

import android.app.AlertDialog
import android.content.DialogInterface
import android.graphics.Bitmap
import android.util.Log
import android.view.View
import android.webkit.CookieManager
import android.webkit.JsPromptResult
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.view.isGone
import com.construction.ccb.R
import com.construction.ccb.base.BaseBindingFragment
import com.construction.ccb.databinding.FragmentWebviewBinding
import com.fido.common.common_base_util.ext.pressBackTwiceToExitApp
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar

class WebViewFragment :BaseBindingFragment<FragmentWebviewBinding>(R.layout.fragment_webview){

    companion object{
        val BUNDLE_URL = "BUNDLE_URL"

        fun getInstance() = WebViewFragment()
    }

    override fun initView() {
        initUI()
        initWeb()
        binding.titleBar.apply {
            title = "我是一个TitleBar"
            setOnTitleBarListener(object :OnTitleBarListener{
                override fun onLeftClick(titleBar: TitleBar?) {
                    activity?.onBackPressed()
                }
            })
        }
        val url = "file:///android_asset/web/index.html"
        binding.webView.loadUrl(url)
    }

    /**
     * @param hide true 隐藏 false 显示
     */
    private fun isHideTitleBar(hide:Boolean=true){
        binding.titleBar.isGone = hide
    }

    private fun initUI() {
        pressBackTwiceToExitApp("再按一次退出")
        immersionBar {
            fitsSystemWindows(true)
            statusBarDarkFont(true)
        }
    }

    override fun initData() {

    }

    private fun initWeb() {
        val webView = binding.webView
        val mWebSettings: WebSettings = webView.settings

        val cookieManager: CookieManager = CookieManager.getInstance()
        cookieManager.setAcceptCookie(true)
        mWebSettings.javaScriptEnabled = true //设置支持javaScript

        mWebSettings.useWideViewPort = true //将图片调整到适合webview的大小

        mWebSettings.loadWithOverviewMode = true // 缩放至屏幕的大小

        mWebSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        mWebSettings.userAgentString = "User-Agent"
        mWebSettings.lightTouchEnabled = true //设置用鼠标激活被选项

        mWebSettings.builtInZoomControls = false //设置支持缩放

        mWebSettings.domStorageEnabled = true //设置DOM缓存，当H5网页使用localStorage时，一定要设置

        mWebSettings.databaseEnabled = true
        mWebSettings.cacheMode = WebSettings.LOAD_NO_CACHE //设置去缓存，防止加载的为上一次加载过的

        mWebSettings.setSupportZoom(true) //设置支持变焦

        webView.isHapticFeedbackEnabled = false
        mWebSettings.pluginState = WebSettings.PluginState.ON
        mWebSettings.allowFileAccess = true
        mWebSettings.allowContentAccess = true
        mWebSettings.allowUniversalAccessFromFileURLs = true
        mWebSettings.allowFileAccessFromFileURLs = true

        webView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                Log.d("MainActivity", "开始加载")
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                Log.d("MainActivity", "加载结束")
            }

            // 链接跳转都会走这个方法
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                Log.d("MainActivity", "Url：$url")
                view.loadUrl(url) // 强制在当前 WebView 中加载 url
                return false
            }
        }

        //设置响应js 的Alert()函数

        //设置响应js 的Alert()函数
        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                Log.d("MainActivity", "newProgress：$newProgress")
            }

            override fun onReceivedTitle(view: WebView?, title: String) {
                super.onReceivedTitle(view, title)
                Log.d("MainActivity", "标题：$title")
            }

            override fun onJsAlert(
                view: WebView?,
                url: String?,
                message: String?,
                result: JsResult
            ): Boolean {
                val b: AlertDialog.Builder = AlertDialog.Builder(this@WebViewFragment.context)
                b.setTitle("")
                b.setMessage(message)
                b.setPositiveButton(android.R.string.ok, DialogInterface.OnClickListener { dialog, which ->
                    result.confirm()
                })
                b.setCancelable(false)
                b.create().show()
                return true
            }

            //设置响应js 的Confirm()函数
            override fun onJsConfirm(
                view: WebView?,
                url: String?,
                message: String?,
                result: JsResult
            ): Boolean {
                val b: AlertDialog.Builder = AlertDialog.Builder(this@WebViewFragment.context)
                b.setTitle("")
                b.setMessage(message)
                b.setPositiveButton(android.R.string.ok,DialogInterface.OnClickListener{ dialog, which ->
                    result.confirm()
                })
                b.setNegativeButton(android.R.string.cancel, DialogInterface.OnClickListener { dialog, which ->
                    result.cancel()
                })
                b.create().show()
                return true
            }

            override fun onJsPrompt(
                view: WebView?, url: String?, message: String?, defaultValue: String?,
                result: JsPromptResult
            ): Boolean {
                result.confirm()
                return super.onJsPrompt(view, url, message, message, result)
            }
        }
    }

}